package com.shanjupay.merchant.service;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.shanjupay.common.constant.Constants;
import com.shanjupay.common.exception.BcException;
import com.shanjupay.common.exception.ErrorCode;
import com.shanjupay.common.util.RandomUtils;
import com.shanjupay.merchant.api.MerchantService;
import com.shanjupay.merchant.api.model.MerchantVO;
import com.shanjupay.merchant.entity.Merchant;
import com.shanjupay.merchant.mapper.MerchantMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.sql.Wrapper;
import java.util.concurrent.TimeUnit;

/**
 * @author xiaoman
 * @version 1.0
 * @date 2021/6/20 19:55
 */

@Service
public class MerchantServiceImpl implements MerchantService {

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public MerchantVO findMerchantById(Long id) {

        Merchant merchant = merchantMapper.selectById(id);
        MerchantVO result = new MerchantVO();
        BeanUtils.copyProperties(merchant, result);
        return result;
    }

    @Override
    public String sendSms(String phone) {
        if (StringUtils.isEmpty(phone)) {
            throw new BcException(ErrorCode.PHONE_EMPTY.getCode(), "手机不能为空");
        } else if (!phone.matches(Constants.PHONE_REGEX)) {
            throw new BcException(ErrorCode.PHONE_FORMAT_ERRO.getCode(), "手机号格式错误");
        }
        Merchant merchantByPhone = merchantMapper.findByMobile(phone);
        if(merchantByPhone != null) {
            throw new BcException(ErrorCode.PHONE_NUMBER_REGISTERED.getCode(), "手机号已注册");
        }

        String codeKey = "VerifyCode" + phone + ":code";
        ValueOperations forValue = redisTemplate.opsForValue();
        String code = RandomUtils.randomNumberStr(6);
        forValue.set(codeKey, code);
        redisTemplate.expire(codeKey, 10 * 60, TimeUnit.SECONDS);
        return code;
    }
}
